const hx = require("hbuilderx");
const hxTheme = require('./theme.js')
const MessageHandler = require('./messageHandler.js')

class ConfigManager {
	constructor(){
		
	}
	static config = {};
	static init() {
		const config = hx.workspace.getConfiguration("ucoder");
		this.config = {
			apiKey: config.get('apiKey', ''),
			baseUrl: config.get('baseUrl', ''),
			codePrompt: config.get('codePrompt', ''),
			codeLine: config.get('codeLine', ''),
			modelName: config.get('modelName', ''),
			chatModelName: config.get('chatModelName', '')
		};

		this.setupListener();
	}
	static configurationListener = null;
	static setupListener() {
		if (this.configurationListener) {
		        this.configurationListener.dispose();
		    }
		this.configurationListener = hx.workspace.onDidChangeConfiguration(function(event) {
			console.log('修改配置')
			const config = hx.workspace.getConfiguration("ucoder");
			if (event.affectsConfiguration("ucoder.apiKey")) {
				this.config.apiKey = config.get('apiKey', '');
				this.notifyChange('updateApiKey', this.config.apiKey);
			}
			if (event.affectsConfiguration("ucoder.baseUrl")) {
				this.config.baseUrl = config.get('baseUrl', '');
				this.notifyChange('updateBaseUrl', this.config.baseUrl);
			}
			if (event.affectsConfiguration("ucoder.codePrompt")) {
				this.config.codePrompt = config.get('codePrompt', '');
			}
			if (event.affectsConfiguration("ucoder.codeLine")) {
				this.config.codeLine = config.get('codeLine', '');
			}
			if (event.affectsConfiguration("ucoder.modelName")) {
				this.config.modelName = config.get('modelName', '');
			}
			if (event.affectsConfiguration("ucoder.chatModelName")) {
				this.config.chatModelName = config.get('chatModelName', '');
				this.notifyChange('updateModelName', this.config.chatModelName);
			}
			if (event.affectsConfiguration("editor.colorScheme") ||
				event.affectsConfiguration("editor.fontSize") ||
				event.affectsConfiguration("editor.fontFamily")) {
				const ThemeColorData = hxTheme.getHBuilderXThemeData();
				this.notifyChange('updateTheme', ThemeColorData);
				console.log('改变主题')
			}
		}.bind(this));
	}

	static notifyChange(command, data) {
		const instance = MessageHandler.getInstance();
		if (instance) {
			instance.postMessage({
				command,
				data
			});
		}
	}
	static getData(key) {
		return this.config[key];
	}
}

// 初始化配置
ConfigManager.init();
console.log('初始化配置')

module.exports = {
	getData: ConfigManager.getData.bind(ConfigManager)
};